var global_id = 0;

function check_and_submit(){
		if(document.getElementById('supplier_name').value == ""){
				alert("Please select a sullpier!");
				return false;
		}
		if(document.getElementById('delivery_address').value == ""){
				alert("Please select a delivery address!");
				return false;
		}
		if(document.getElementById('balance_account').value == ""){
				alert("Please select a DR Account!");
				return false;
		}
		document.getElementById('form1').submit();
}
function enable_tax(){
        if(document.getElementById("tr3_tax").style.display=="none"){
            document.getElementById("tr3_tax").style.display="block";
            document.getElementById("tr3_empty").style.display="block";            
            //default_tax_checkbox();
        }else{
            document.getElementById("tr3_tax").style.display="none";
            document.getElementById("tr3_empty").style.display="none";
            //default_tax_checkbox();
        }        
}
function set_address(){
        var supplier_info = document.getElementById("supplier_info").value;
        if(supplier_info!=''){
                supplier_info_array = supplier_info.split('|');
                document.getElementById("td1").innerHTML = '<span class="fin-to">To : </span>'+supplier_info_array[0];
                var addr_str = supplier_info_array[1]+','+supplier_info_array[2]+','+supplier_info_array[3]+' '+supplier_info_array[4]+' '+supplier_info_array[5]+','+supplier_info_array[6];
                document.getElementById("td2").innerHTML = addr_str;   
                document.getElementById("td3").innerHTML ='{{abn_label}}:'+supplier_info_array[7];
                document.getElementById("supplier_name").value =supplier_info_array[0];
        }else{
                document.getElementById("td1").innerHTML = '';
                document.getElementById("td2").innerHTML = '';
                document.getElementById("td3").innerHTML = '';
                document.getElementById("supplier_name").value = '';
        }
}

function set_delivery_address(){
        var delivery_add = document.getElementById("delivery_address").value;
        if(delivery_add!=''){
                delivery_add_array = delivery_add.split('|');
                var addr_str = delivery_add_array[1]+','+delivery_add_array[2]+','+delivery_add_array[3]+' '+delivery_add_array[4]+' '+delivery_add_array[5]+','+delivery_add_array[6];
                document.getElementById("da").innerHTML = addr_str;   
        }else{
                document.getElementById("da").innerHTML = '';
        }
}

function push(){   
		document.getElementById("tr3_item").value="";  
		document.getElementById("tr3_qty").value="";
		document.getElementById("tr3_unit_price").value="";  
		document.getElementById("tr3_empty").style.display="none";
		document.getElementById("tr3_tax").style.display="none";
		var tax_list = document.getElementsByName("set_tax");
		{% if default_tax %}
			for(i=0;i<tax_list.length;i++)
			{
					tax_id = tax_list[i].value.split('|')[1];
					if(parseInt(tax_id) == parseInt({{default_tax['default_tax_id']}}))
					{
							tax_list[i].checked = true;
					}
					else
					{
							tax_list[i].checked = false;
					}
			}
		{% endif %}
} 
Array.prototype.unique   = function()  
{  
        var   o   =   new   Object();  
        for   (var   i=0,j=0;   i<this.length;   i++)  
        {  
                if   (typeof   o[this[i]]   ==   'undefined')  
                {  
                        o[this[i]]   =   j++;  
                }  
        }  
        this.length   =   0;  
        for   (var   key   in   o)  
        {  
                this[o[key]]   =   key;  
        }  
        return   this;  
}  
function check_tax_list()
{
        var have_choose_tax = false;
        var tax_list = document.getElementsByName("set_tax");
        for(i=0;i<tax_list.length;i++)
        {
                if(tax_list[i].checked)
                {
                        have_choose_tax = true;
                        break;
                }
        }
        return have_choose_tax;
}
function check_value()
{
        var item = document.getElementById("tr3_item").value;
        var qty = document.getElementById("tr3_qty").value;
        var unit_price = document.getElementById("tr3_unit_price").value;
        
        var bool = true;
        
        if(item==""||qty==""||unit_price=="")
        { 
                bool = false;
        }
        if(qty!="" && isNaN(parseInt(qty)))
        {
                document.getElementById('tr3_qty').value = "";
                bool = false;
        }
        if(unit_price!="" && isNaN(parseFloat(unit_price)))
        {
                document.getElementById('tr3_unit_price').value = "";
                bool = false;
        }
        //if(!check_tax_list())
        //{
        //        bool = false;
        //}
        return bool;
}
function sum_tax_percent(tax_list_name)
{
        var total_tax_percent = 0;
        var tax_list = document.getElementsByName(tax_list_name);
        for(i=0;i<tax_list.length;i++)
        {
                if(tax_list[i].checked)
                {
                        total_tax_percent = Math.round((total_tax_percent+parseFloat(tax_list[i].value.split('|')[2]))*100)/100;
                }
        }
        return total_tax_percent;
}

function sum_item_tax_percent(tax_list_name)
{
        var total_item_tax_percent = 0;
        var tax_list = document.getElementsByName(tax_list_name);
        for(i=0;i<tax_list.length;i++)
        {
                total_item_tax_percent = Math.round((total_item_tax_percent+parseFloat(tax_list[i].value.split('|')[2]))*100)/100;
        }
        return total_item_tax_percent;
}

function sum_total_include_tax_percent(tax_list_name)
{
        var total_include_tax_percent = 0;
        var tax_list = document.getElementsByName(tax_list_name);
        for(i=0;i<tax_list.length;i++)
        {
                if(tax_list[i].checked)
                {
                        if(tax_list[i].value.split('|')[3] == 'True')
                        {
                                total_include_tax_percent = Math.round((total_include_tax_percent+parseFloat(tax_list[i].value.split('|')[2]))*100)/100;
                        }
                }
        }
        return total_include_tax_percent;
}

function total_amount_exclude_tax(qty, unit_price, total_include_tax_percent)
{
        var subtotal = 0;
        if(total_include_tax_percent == 0)
        {
                subtotal = Math.round(parseInt(qty)*parseFloat(unit_price)*100)/100;
        }
        else
        {
                subtotal = Math.round(parseInt(qty)*parseFloat(unit_price)/(1+parseFloat(total_include_tax_percent)/100)*100)/100;
        }
        return subtotal;
}

function tax_amount(subtotal, total_tax_percent)
{
        return Math.round(subtotal*parseFloat(total_tax_percent)/100*100)/100;
}

function total_amount_include_tax(subtotal, tax_amount)
{
        return Math.round((subtotal+tax_amount)*100)/100;
}

function tax_list_html(item_id)
{
        var html = '';
        var tax_list = document.getElementsByName("set_tax");
        for(i=0;i<tax_list.length;i++)
        {
                if(tax_list[i].checked)
                {
                        if(tax_list[i].value.split('|')[3] == 'True')
                        {
                                html += '<input type="checkbox" name="tax_item_'+item_id+'" value="'+tax_list[i].value+'" checked="checked" onclick="recalculate_tax('+item_id+')"/>'+tax_list[i].value.split('|')[0];
                        }
                        else
                        {
                                html += '<input type="checkbox" name="tax_item_'+item_id+'" value="'+tax_list[i].value+'" onclick="recalculate_tax('+item_id+')"/>'+tax_list[i].value.split('|')[0];
                        }
                }
        }
        html += '<input type="hidden" id="tax_id_list_' + item_id + '" name="tax_id_list" value="' + get_tax_id_list() + '"/><input type="hidden" id="tax_inclusions_list_' + item_id + '" name="tax_inclusions_list" value="' + get_tax_inclusions_list() + '"/>';
        return html;
}

function change_tax_inclusions(item_id)
{
        var tax_list = document.getElementsByName('tax_item_'+item_id);
        var inclusions_list = '';
        for(i=0;i<tax_list.length;i++)
        {
                if(tax_list[i].checked)
                {
                        tax_list[i].value = tax_list[i].value.split('|')[0] +'|'+tax_list[i].value.split('|')[1] +'|'+tax_list[i].value.split('|')[2] +'|'+'True';
                        inclusions_list += 'True,';
                }
                else
                {
                        tax_list[i].value = tax_list[i].value.split('|')[0] +'|'+tax_list[i].value.split('|')[1] +'|'+tax_list[i].value.split('|')[2] +'|'+'False';
                        inclusions_list += 'False,';
                }
        }
        document.getElementById('tax_inclusions_list_'+item_id).value = inclusions_list;
}

function recalculate_tax(item_id)
{
        change_tax_inclusions(item_id.toString());
        var obj = document.getElementById("row"+item_id.toString());
        var qty = document.getElementById("qty_"+item_id.toString()).value;
        var unit_price = document.getElementById("unit_price_"+item_id.toString()).value;
        var subtotal = total_amount_exclude_tax(qty,unit_price,sum_total_include_tax_percent('tax_item_'+item_id.toString()));
        var tax_total = tax_amount(subtotal, sum_item_tax_percent('tax_item_'+item_id.toString()));
        var amount = total_amount_include_tax(subtotal, tax_total);
        obj.childNodes[3].innerHTML = subtotal.toString();
        obj.childNodes[4].innerHTML = tax_total.toString();
        obj.childNodes[5].innerHTML = amount.toString();
        calculate_separate_tax_amount();
        sum_total();
}

function calculate_separate_tax_amount()
{
        var table_obj = document.getElementById("for_display");
        
        {% for tax in taxes %}
                document.getElementById("fpc_{{tax['id']}}_amount").innerHTML = 0;
                for(i=1;i<global_id+1;i++)
                {
                        var re = new RegExp({{tax['id']}});
                        if(document.getElementById('tax_id_list_'+(i-1).toString()).value.search(re) != -1)
                        {
                                document.getElementById("fpc_{{tax['id']}}_amount").innerHTML = (Math.round((parseFloat(document.getElementById("fpc_{{tax['id']}}_amount").innerHTML)+parseFloat(document.getElementById('row'+(i-1)).childNodes[3].innerHTML)*parseFloat({{tax['rate']}})/100)*100)/100).toString();
                                document.getElementById("fpc_{{tax['id']}}_field").style.display="block";
                        }
                }
        {% endfor %}
}

function get_tax_id_list()
{
        var tax_id_list = "";
        var tax_list = document.getElementsByName("set_tax");
        for(j=0;j<tax_list.length;j++)
        {
                if(tax_list[j].checked)
                {
                        tax_id_list += tax_list[j].value.split('|')[1]+",";
                }
        }
        return tax_id_list;
}
function get_tax_inclusions_list()
{
        var tax_inclusions_list = "";
        var tax_list = document.getElementsByName("set_tax");
        for(j=0;j<tax_list.length;j++)
        {
                if(tax_list[j].checked)
                {
                        tax_inclusions_list += tax_list[j].value.split('|')[3]+",";
                }
        }
        return tax_inclusions_list;
}

function sum_total()
{
        var total_subtotal = 0;
        var total_tax = 0;
        var total_amount = 0;
        
        var table_obj = document.getElementById("for_display");
        for(i=0;i<global_id;i++)
        {
                total_subtotal = Math.round((total_subtotal+parseFloat(document.getElementById('row'+i).childNodes[3].innerHTML))*100)/100;
                total_tax = Math.round((total_tax+parseFloat(document.getElementById('row'+i).childNodes[4].innerHTML))*100)/100;
                total_amount = Math.round((total_amount+parseFloat(document.getElementById('row'+i).childNodes[5].innerHTML))*100)/100;
        }
        
        document.getElementById('th_subtotal').innerHTML = total_subtotal.toString();
        document.getElementById('th_tax').innerHTML = total_tax.toString();
        document.getElementById('th_amount').innerHTML = total_amount.toString();
        
        document.getElementById('td_subtotal').innerHTML = total_subtotal.toString();
        document.getElementById('td_amount').innerHTML = total_amount.toString();
}

function check_kinds_of_tax()
{
        var all_tax_id_array = new Array();
        var tax_in_item = document.getElementsByName("tax_id_list");
        for(j=0;j<tax_in_item.length;j++)
        {
                all_tax_id_array = all_tax_id_array.concat(tax_in_item[j].value.split(',').slice(0,-1));
        }
        if(all_tax_id_array.unique().length > 1)
        {
                document.getElementById("tax_in_field_name_1").innerHTML = "Subtotal<br/>(excl Tax)";
                document.getElementById("tax_in_field_name_2").innerHTML = "Tax amount";
                document.getElementById("tax_in_field_name_3").innerHTML = "Amount payable<br/>(incl Tax)";
                document.getElementById("tax_in_total_field_1").innerHTML = "Total (excl Tax)";
                document.getElementById("tax_in_total_field_2").innerHTML = "Total Invoice (incl Tax)";
        }else{
                {% for tax in taxes %}
                        if(parseInt({{tax['id']}}) == parseInt(all_tax_id_array.unique()[0]))
                        {
                                document.getElementById("tax_in_field_name_1").innerHTML = "Subtotal<br/>(excl {{tax['shortname']}})";
                                document.getElementById("tax_in_field_name_2").innerHTML = "{{tax['shortname']}} amount";
                                document.getElementById("tax_in_field_name_3").innerHTML = "Amount payable<br/>(incl {{tax['shortname']}})";
                                document.getElementById("tax_in_total_field_1").innerHTML = "Total (excl {{tax['shortname']}})";
                                document.getElementById("tax_in_total_field_2").innerHTML = "Total Invoice (incl {{tax['shortname']}})";
                        }
                {% endfor %}
        }
}
function add_row()
{

        var obj = document.getElementById("for_display");
        var bottom = document.getElementById("for_display_bottom");        
        
        if(check_value())
        {
                var item_id = global_id;
                var str_item_id = item_id.toString();                

                var dl=document.createElement('dl');
                dl.setAttribute('class','dl2');
                dl.setAttribute('className','dl2');
                dl.setAttribute('id','row'+item_id);
                
                var dd=document.createElement('dd');
                dd.setAttribute('class','dd');
                dd.setAttribute('className','dd'); 
                var item = document.getElementById("tr3_item").value;
                dd.innerHTML = '<div style="display:none"><textarea name="description">'+item+'</textarea></div>'+escapeHTML(item);
                dl.appendChild(dd);
                
                var dd=document.createElement('dd');
				dd.setAttribute('class','dd2');
                dd.setAttribute('className','dd2'); 
                var qty = document.getElementById("tr3_qty").value;
                dd.innerHTML = '<input type="hidden" id="qty_'+str_item_id+'" name="qty" value="'+qty+'"/>'+qty;
                dl.appendChild(dd);
                
                var dd=document.createElement('dd');
				dd.setAttribute('class','dd2');
                dd.setAttribute('className','dd2'); 
                var unit_price = document.getElementById("tr3_unit_price").value;
                dd.innerHTML = '<input type="hidden" id="unit_price_'+str_item_id+'" name="unit_price" value="'+unit_price+'"/>'+unit_price;
                dl.appendChild(dd); 
                
                var subtotal = total_amount_exclude_tax(qty,unit_price,sum_total_include_tax_percent("set_tax"));
                var tax_total = tax_amount(subtotal, sum_tax_percent("set_tax"));
                var amount = total_amount_include_tax(subtotal, tax_total);
                
                var dd=document.createElement('dd');
                dd.innerHTML = subtotal.toString();
                dl.appendChild(dd);
                
                var dd=document.createElement('dd');
                dd.innerHTML = tax_total.toString();
                dl.appendChild(dd);
                
                var dd=document.createElement('dd');
                dd.setAttribute('class','dd3');
                dd.setAttribute('className','dd3');
                dd.innerHTML = amount.toString();                
                dl.appendChild(dd);
                
                var dt=document.createElement('dt');
                dt.innerHTML = tax_list_html(str_item_id);
                dl.appendChild(dt);
                obj.insertBefore(dl,bottom);
                global_id ++;
                check_kinds_of_tax();
                push();
                
                calculate_separate_tax_amount();
                sum_total();                
        }
}
